﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QLTour.Ultilities
{
    public class DatabaseHelper
    {
        private SqlConnection conn;
        private SqlCommand cmd;

        public DatabaseHelper()
        {
            string path = Directory.GetCurrentDirectory();
            string connectString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"" + path.Substring(0, path.Length - "\\bin\\Debug".Length) + "\\Database\\TourDbs.mdf\";Integrated Security=True";
            conn = new SqlConnection(connectString);
        }

        private void Connect()
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
        }

        public void Close()
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }

        public object GetValue(string query)
        {
            Connect();
            cmd = new SqlCommand(query, conn);
            return cmd.ExecuteScalar();
        }

        public DataTable GetDateTable(string select)
        {
            SqlDataAdapter da = new SqlDataAdapter(select, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);

            return dt;
        }
        public SqlDataReader Reader(string query)
        {
            Connect();
            SqlCommand command = new SqlCommand(query, conn);
            SqlDataReader reader = command.ExecuteReader();
            return reader;
        }
        public int ExecuteNonQuery(string query)
        {
            Connect();
            cmd = new SqlCommand(query, conn);
            return cmd.ExecuteNonQuery();
        }
    }
}
